//
// HighlightBlocks.cs
//
// Author: 
//  Fredy Ramirez <framirez@pacificcoolwave.com>
//
// Copyright (C) 2011 Fredy Ramirez (http://www.pacificcoolwave.com)
//
//  Creation date: Nov 24, 2011
//  Last modification: 

/*
The MIT License

Copyright (C) 2011 Fredy Ramirez (http://www.pacificcoolwave.com)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
 */

using System;
using Pcw.PcwTextEditor;
using Pcw.PcwTextEditor.PcwDocument;
using System.Collections.Generic;
using Gtk;

namespace Pcw.Addins.Highlighting.Definition
{
	internal enum BetweenBlockResult 
	{
		NoInBlock,
		InRange,
		EndOpenBlock,
		BreakStartBlock,
		BreakEndBlock
	}
	
	internal enum BlockStatus
	{
		Completed,
		Incompleted,
		AllDeleted,
		BeginDeleted,
		EndDeleted
	}	
	
	public class HighlightBlocks
	{		
		private SortedList<int, HlBlock> blocks = new SortedList<int, HlBlock>();

		internal SortedList<int, HlBlock> Blocks {
			get {
				return blocks;
			}
		}
		
		public HighlightBlocks ()
		{
		}

		internal void AddBlock(int startOffset, HlBlock block) 
		{
			Console.WriteLine("ADDING BLOCK: start: {0} - end: {1}", block.StartOffset, block.EndOffset);
			blocks.Add(startOffset, block);
		}
		
		internal BetweenBlockResult VerifyBetweenBlock (TextChangedInfo info, out HlBlock resultBlock, 
		                                                out HlBlock beforeBlock, out HlBlock afterBlock)
		{
			/*
			NoInBlock,
			InRange,
			EndOfOpenBlock,
			BreakStartBlock,
			BreakEndBlock			
			*/
			
			resultBlock = null;
			beforeBlock = null;
			afterBlock = null;
			
			if (blocks.Count == 0)
				return BetweenBlockResult.NoInBlock;
			
			BetweenBlockResult result = BetweenBlockResult.NoInBlock;
			
			int x = 0;
			foreach (var pair in blocks) {				
				HlBlock b = pair.Value;				
				if (info.StartOffset > b.BlockStartOffset && info.StartOffset < b.BlockEndOffset)  {					
					if (info.ChangeType == TextChangeType.InsertText && (
					    (b.Descriptor.HlType == HighlightType.ToEOL && info.StartOffset == b.BlockEndOffset - 2) || 
						(b.Descriptor.HlType == HighlightType.ToCloseToken && b.Status != BlockStatus.Completed)))
						result = BetweenBlockResult.EndOpenBlock; //It is at the end of ToEOL or at the end of open block (not completed).
					else
						result = BetweenBlockResult.InRange;
					
					resultBlock = b;
					break;
				}
			}
			
			if(result == BetweenBlockResult.NoInBlock)
				GetBlocksNoInBLock(info.StartOffset, info.EndOffset, ref beforeBlock, ref afterBlock);
			
			return result;
		}
		
		private void GetBlocksNoInBLock(int startOffset, int endOffset, ref HlBlock beforeBlock, ref HlBlock afterBlock) 
		{
			foreach (var pair in blocks) 
			{
				if(pair.Value.EndOffset <= startOffset)
					beforeBlock = pair.Value;
				if(pair.Value.StartOffset > endOffset)
					break;
			}
			foreach (var pair in blocks) 
			{
				if(pair.Value.StartOffset > endOffset) {
					afterBlock = pair.Value;
					break;
				}
			}
		}
		
		/*
		internal HighlightBlock GetBlockInRange(int startOffset) 
		{
			foreach (HighlightBlock b in blocks){
				if (startOffset > b.StartOffset && startOffset < b.EndOffset) 
					return b;
			}
			
			return null;
		}
		
		internal void VerifyBlocks (TextBuffer buffer, TextChangedInfo info) 
		{
			if (info == null || blocks.Count == 0)
				return;
			
			int diffOffset = info.EndIter.Offset - info.StartIter.Offset;
			int diffLine = info.EndLine - info.StartLine;
			
			if (info.ChangeType == TextChangeType.DeleteText) {
				diffOffset = diffOffset * -1;
				diffLine = diffLine * -1;
			}
			
			string sKey = "";
			TextIter sIter, eIter;
			
			foreach (HighlightBlock b in blocks){			
				b.AdjustOffset(info, diffOffset, diffLine);
				
				// Verify if an existing block still has an open key.
				sKey = TextEditor.GetStringOfsset(buffer, b.StartOffset, ref sIter, b.StartOffset + b.Descriptor.Key.Length, ref eIter);
				if (sKey != b.Descriptor.Key) {
					TextEditor.RemmoveAllTagsFromOffset(buffer, b.StartOffset, b.EndOffset);
					blocks.Remove(b);
				}
			}
		}
		*/
	}
	
	internal class HlBlock 
	{
		private TextBuffer buffer;
		private int start_offset = -1;
		private int end_offset = -1;
		private BlockStatus status = BlockStatus.Incompleted;
		private int start_line = -1;
		private int end_line = -1;
		private Descriptor descriptor;
	
		internal int StartOffset {
			get {
				return start_offset;
			}
		}
		
		internal int BlockStartOffset {
			get {
				return start_offset + (descriptor.Key.Length - 1);
			}
		}
		
		internal int BlockEndOffset {
			get {
				if (descriptor.HlType == HighlightType.ToEOL || status != BlockStatus.Completed)
					return end_offset + 1;
				
				return end_offset - (descriptor.CloseToken.Length - 1);
			}
		}
		
		internal int EndOffset {
			get {
				return end_offset;
			}
			set {
				end_offset = value;
				TextIter iter = buffer.StartIter;
				iter.ForwardChars(end_offset);
				end_line = iter.Line;
			}
		}
		
		internal int StartLine {
			get {
				return start_line;
			}
		}
		
		internal int EndLine {
			get {
				return end_line;
			}
		}		
		
		internal BlockStatus Status {
			get {
				return status;
			}
			set {
				status = value;
			}
		}

		internal Descriptor Descriptor {
			get {
				return descriptor;
			}
		}
		
		internal HlBlock(TextBuffer buffer, int startOffset, int endOffset, BlockStatus status, Descriptor descriptor)
		{
			this.buffer = buffer;
			
			start_offset = startOffset;
			end_offset = endOffset;
			
			TextIter iter = buffer.StartIter;
			iter.ForwardChars(start_offset);
			start_line = iter.Line;
			iter = buffer.StartIter;
			iter.ForwardChars(end_offset);
			end_line = iter.Line;
			
			this.status = status;
			this.descriptor = descriptor;
			
			// For testing
			//Console.WriteLine("BLOCK TEXT: {0}", GetBlockText());
		}
		
		// return false if this block have been deleted or broken.
		internal bool AdjustOffset (TextChangedInfo info) 
		{
			if (info.StartOffset > end_offset)
				return true;

			if(info.StartOffset == end_offset) { 
				if (descriptor.HlType == HighlightType.ToCloseToken && status == BlockStatus.Completed)
					return true;
				if (descriptor.HlType != HighlightType.ToEOL && descriptor.HlType != HighlightType.ToCloseToken)
					return true;
			}
			
			// All block were deleted
			if (info.StartOffset < start_offset && info.EndOffset > end_offset) {
				status = BlockStatus.AllDeleted;
				return false;
			}
			
			// TODO Set the status of block
			
			
			
			
			// Adjust
			if (info.StartOffset <= BlockStartOffset)
				start_offset = start_offset + info.CharsAffected;
			
			if (info.StartOffset < BlockEndOffset)
				end_offset = end_offset + info.CharsAffected;
			
			if (info.LinesAffected > 1) {
				if (info.StartLine < start_line)
					start_line = (StartLine + info.LinesAffected) - 1;

				if (info.EndLine < end_line)
					end_line = (end_line + info.LinesAffected) - 1;	
			}
			
			return true;
		}
		
		private string GetBlockText() 
		{
			TextIter start = buffer.StartIter;
			start.ForwardChars(start_offset);
			TextIter end = buffer.StartIter;
			end.ForwardChars(end_offset);
			return buffer.GetText(start, end, true);
		}		
	}
}

